<template>
    <el-upload ref="upload" class="custom_upload" v-bind="uploadProps">
        <template v-if="contentSlot">
            <virtual-node :render="contentSlot" />
        </template>
        <template v-else-if="$scopedSlots.default">
            <slot />
        </template>
    </el-upload>
</template>

<script>
import Vue from 'vue';
import { ElUpload } from "../../form/Dynamic/attributes";
import ajax from 'element-ui/packages/upload/src/ajax';

export default {
    name: "CustomElUpload",
    components: {
        VirtualNode: Vue.extend({
            functional: true,
            props: {
                render: Function,
            },
            render(h, ctx) {
                if (typeof ctx.props.render === 'function') {
                    return ctx.props.render(h, ctx.parent);
                }
            },
        }),
    },
    props: {
        options: {
            type: Object,
            default: null,
        },
        disabled: {
            type: Boolean,
            default: null,
        },
        contentSlot: {
            type: Function,
            default: null,
        },
    },
    data() {
        return {
            defaultProps: {
                ...ElUpload,
                httpRequest: ajax,
            },
            event: {
                change() {},
            },
        };
    },
    computed: {
        uploadProps() {
            let props = $.extend({}, this.defaultProps);
            if (this.options) {
                for (let field in this.defaultProps) {
                    if (typeof this.options[field] !== 'undefined') {
                        props[field] = this.options[field];
                    }
                    let propsFn = this.options[`${ field }Fn`];
                    if (typeof propsFn === 'function') {
                        props[field] = propsFn.call(this.options);
                    }
                }
            }
            if (this.disabled) {
                props.disabled = this.disabled;
            }
            delete props.slots;
            return props;
        },
    },
    methods: {
        clearFiles() {
            this.$refs.upload.clearFiles();
        },
        abort(file) {
            this.$refs.upload.abort(file);
        },
        submit() {
            this.$refs.upload.submit();
        },
        upload() {
            let upload = this.$refs.upload;
            if (!upload) {
                return;
            }
            let uploadInner = upload.$refs['upload-inner'];
            if (!uploadInner) {
                return;
            }
            uploadInner.$refs.input.click();
        },
    },
}
</script>

<style scoped lang="less">

</style>